/*
 * Model.java
 *
 * 02/11/2009
 */
package kg.sound.player;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;

import kg.sound.player.media.MediaWrapper;
import org.apache.commons.collections.Predicate;
import org.apache.commons.collections.iterators.FilterIterator;

/**
 * @author fernando
 */
public class Model {

	private final HashMap<File, MediaWrapper> playlist = new HashMap<File, MediaWrapper>();
	private final ModelListeners listeners = new ModelListeners();

	public Iterator<File> playlist() {
		return playlist.keySet().iterator();
	}

	public ModelListeners getListeners() {
		return listeners;
	}

	@SuppressWarnings("unchecked")
	public Iterator<File> playingNow() {
		return new FilterIterator(playlist(), new Predicate() {
			@Override
			public boolean evaluate(Object file) {
				MediaWrapper clip = playlist.get(file);
				return clip.isPlaying();
			}
		});
	}

	public boolean isPlaying(File file) {
		if (playlist.containsKey(file)) {
			return playlist.get(file).isPlaying();
		}
		return false;
	}

	public void playClip(File file) throws Exception {
		if (playlist.containsKey(file)) {
			playlist.get(file).playClip();
		}
	}

	public void playStream(File file) throws Exception {
		if (playlist.containsKey(file)) {
			playlist.get(file).playStream();
		}
	}

	public void stop(File file) {
		if (playlist.containsKey(file)) {
			playlist.get(file).stop();
		}
	}

	public void addMedia(File... files) {
		for (File file : files) {
			if (!playlist.containsKey(file)) {
				MediaWrapper media = new MediaWrapper(file);
				media.getListeners().add(getListeners());
				playlist.put(file, media);
			}
		}
		getListeners().firePlaylistChanged();
	}
	
	public void removeMedia(File... files) {
		for (File file : files) {
			if (playlist.containsKey(file)) {
				if (isPlaying(file)) {
					playlist.get(file).stop();
				}
				playlist.remove(file);
			}
		}
		getListeners().firePlaylistChanged();
	}
	
	public void clearPlaylist() {
		removeMedia(playlist.keySet().toArray(new File[0]));
	}
}
